# note/views.py

from django.shortcuts import render, redirect
from .import models
from django.urls import reverse
from django.views.generic.base import View
from operation.models import LabelProfile
from django.http import HttpResponseRedirect
# Create your views here.


class IndexNoteView(View):
    '''首页'''

    def get(self, request):
        notes = models.NoteProfile.objects.all().order_by('-last_saved')
        labels = LabelProfile.objects.all()
        return render(request, 'index-note.html', {'notes': notes, 'labels': labels})


class NoteHrefView(View):
    '''文章链接'''
    def get(self, request, note_id):
        note = models.NoteProfile.objects.get(pk=note_id)
        note.note_reading_quantity += 1
        note.save()
        note_comments = models.note_comment_profile.objects.filter(note_id=note_id).order_by(
            '-note_comment_published_time')
        return render(request, 'note.html', {'note': note, 'note_comments': note_comments})


class NewNoteView(View):
    '''新文章'''
    def get(self, request):
        labels = LabelProfile.objects.all()
        return render(request, 'edit-note.html', {'labels': labels})

    def post(self, request):
        user = request.user
        note_title = request.POST.get('title', None)
        note_content = request.POST.get('content', None)
        labellist = request.POST.getlist("label")
        label = models.LabelProfile.objects.all()
        newnote = models.NoteProfile.objects.create(userprofile_id=user, note_title=note_title, note_content=note_content)
        for i in label:
            if i.label_content in labellist:
                newnote.note_label.add(i)
        return HttpResponseRedirect(reverse('note:index-note'))


def note_comment_action(request):
    '''评论'''
    user = request.user
    note_comment_content = request.POST.get('note_comment', None)
    note_id = request.POST.get('note_id', None)
    note = models.NoteProfile.objects.get(pk=note_id)
    note_comment_userprofile_id = request.POST.get('comment_userprofile_id', None)
    if note_comment_userprofile_id == '':
        models.note_comment_profile.objects.create(userprofile_id=user, note_id=note,
                                                   note_comment_content=note_comment_content)
    else:
        comment_userprofile_id = models.UserProfile.objects.get(username=note_comment_userprofile_id)
        models.note_comment_profile.objects.create(userprofile_id=user, note_comment_userprofile_id=comment_userprofile_id,
                                                   note_comment_content=note_comment_content,
                                                   note_id=note)
    referer = request.META.get('HTTP_REFERER', reverse('note:index-note'))
    return redirect(referer)
